<?php

namespace app\api\controller;

use app\common\controller\Api;
use EasyWeChat\Factory;
use think\Request;
use app\admin\model\Order;
use app\api\model\Collection;
use app\api\model\UserWeixin;

/**
 * 小程序接口
 */
class Weixin extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    protected $miniapp;
    protected $payment;
    /**
     * 初始化
     *
     */
    public function __construct()
    {
        $config=[
            'app_id'=>'',
            'secret'=>'',
            'mch_id'=>'',
            'key'=>'',
            'notify_url'=>Request::instance()->domain().'/api/weixin/notify'

        ];
        $this->miniapp=Factory::miniProgram($config);
        $this->payment=Factory::payment($config);
    }
    /**
     * 登陆
     *
     */
    public function login($code)
    {
        $res=$this->miniapp->session($code);
        $user=new UserWeixin;
        $user->allowField(true)->save($res);
        $this->success('请求成功',$res);
    }
    /**
     * 保存和获取用户信息
     *
     */
    public function userInfo()
    {
        $params=Request::instance()->params();
        $user=UserWeixin::get(['openid'=>$params['openid']]);
        if(is_null($user->nickName)){
            $user->allowField(true)->save($params);
        }
        $this->success('请求成功',$user);
    }
    /**
     * 下单
     *
     */
    public function createOrder()
    {
        $params=Request::instance()->params();
        $params['out_trade_no']=date('YmdHis',time()).rand(0,9999);
        Order::create($params);
        $res=$this->payment->order->unify([
            'openid'=>$params['openid'],
            'body'=>'',
            'out_trade_no'=>$params['out_trade_no'],
            'total_fee'=>$params['total_fee']*100,
            'trade_type'=>'JSAPI'
        ]);
        $this->success('请求成功',$res);
    }
    /**
     * 收藏
     *
     */
    public function collection()
    {
        $params=Request::instance()->params();
        if(array_get($params,'type')){
            if($params['type']==='delete'){
                Collection::destroy($params['course_id']);
            }
            if($params['type']==='add'){
                COllection::create(['openid'=>$params['openid'],'course_id'=>$params['course_id']]);
            }
        }
        $res=Collection::all(['openid'=>$openid]);
        $this->success('请求成功',$res);
    }
    
    /**
     * 支付结果通知
     *
     */
    public function notify()
    {
        $response = $app->handlePaidNotify(function($message, $fail){
            $order = Order::get(['out_trade_no'=>$message['out_trade_no']]);
            if (!$order || $order->stauts===1) { 
            return true; 
            }

            if ($message['return_code'] === 'SUCCESS') { 
                if (array_get($message, 'result_code') === 'SUCCESS') {
                $order->status = 1;

                } elseif (array_get($message, 'result_code') === 'FAIL') {
                $order->status = 0;
                }
            } else {
            return $fail('通信失败，请稍后再通知我');
            }

            $order->save(); 

            return true; 
            });

        return $response;
    }
}
